<?php

namespace app\api\controller\v1;

use app\admin\model\Litestorecart;
use app\common\controller\Api;
use addons\litestore\model\Wxlitestoregoods;
use addons\litestore\model\Litestoregoodsspec;

class Goods extends Api
{
    protected $noNeedLogin = ['category_list','detail'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
    }

    public function detail()
    {
        $goods_id = $this->request->param('goods_id');

        // 商品详情
        $detail = Wxlitestoregoods::detail($goods_id);
        $imgs = [];
        foreach (explode(",", $detail['images']) as $index => $item) {
            $imgs[] = cdnurl($item, true);
        }
        $detail['imgs_url'] = $imgs;

        if (!$detail || $detail['goods_status'] !== '10') {
            $this->error('很抱歉，商品信息不存在或已下架');
        }
        // 规格信息
        $specData = $detail['spec_type'] === '20' ? $detail->getNewManySpecData($detail['spec_rel'], $detail['spec']) : null;

        // 这里对规格的img格式化
        if ($specData != null) {
            foreach ($specData['spec_list'] as $index => $item) {
                $specData['spec_list'][$index]["form"]['imgshow'] = $specData['spec_list'][$index]["form"]['spec_image'] === '' ? null : cdnurl($specData['spec_list'][$index]["form"]['spec_image'], true);
            }
        }
        $detail['content'] = preg_replace(
            array(
                '/(<img [^<>]*?)width=.+?[\'|\"]/',
                '/(<img.*?)((height)=[\'"]+[0-9|%]+[\'"]+)/',
                '/(<img.*?)((style)=[\'"]+(.*?)+[\'"]+)/',
            ) , array('$1 width="90%" ', '$1', '$1') , $detail['content']);

        $images = explode(",",$detail['images']);
        foreach ($images as $k=>$v){
            $images[$k] =  cdnurl($v,true);
        }

        $user = $this->auth->getUser();

        $role = array();
        $price=  $detail['spec'][0]['goods_price'];
        $userRatio = 0;
        if($user){


            if($user['group_id'] == 1){
                $role['name'] = 'U粉丝';
                $role['price'] = $price;
                $userRatio = 100;
            }else if($user['group_id'] == 2){
                $role['name'] = 'U品推荐官';
                $userRatio = $detail['oneRatio'];

                $role['price'] = sprintf("%.2f",$price*$detail['oneRatio']/100) ;
            }else if($user['group_id'] == 3){
                $role['name'] = 'U品代言人';
                $role['price'] =   sprintf("%.2f",$price*$detail['twoRatio']/100 );
                $userRatio = $detail['twoRatio'];

            }else if($user['group_id']== 4){
                $role['name'] = 'U品合伙人';
                $userRatio = $detail['threeRatio'];
                $role['price'] = sprintf("%.2f",$price*$detail['threeRatio']/100 );;
            }
        }

        $rank= array();
        $rankDetail = array();
        $rankDetail['name']= 'U品推荐官';
        $rankDetail['price']= sprintf("%.2f",$price*$detail['oneRatio']/100);
        $rankDetail['make']= sprintf("%.2f",($price-$price*$detail['oneRatio']/100));
        $rank[] = $rankDetail;

        $rankDetail = array();
        $rankDetail['name']= 'U品代言人';
        $rankDetail['price']= sprintf("%.2f",$price*$detail['twoRatio']/100);
        $rankDetail['make']= sprintf("%.2f",($price-$price*$detail['twoRatio']/100));
        $rank[] = $rankDetail;

        $rankDetail = array();
        $rankDetail['name']= 'U品合伙人';
        $rankDetail['price']= sprintf("%.2f",$price*$detail['threeRatio']/100);
        $rankDetail['make']= sprintf("%.2f",($price-$price*$detail['threeRatio']/100));
        $rank[] = $rankDetail;


        $litestoreCartModel = new Litestorecart();
        $total_cart_num = $litestoreCartModel->getTotalNum($user['id']);
        $detail['images'] = $images;
        $this->success('', [
            'detail' => $detail,
            'specData' => $specData,
            'role' =>$role,
            'rank'=>$rank,
            'ratio' =>$userRatio,
            'total_cart_num'=>$total_cart_num
        ]);
    }

    public function category_list()
    {
        $categoryid = $this->request->param('id');
        $page = $this->request->param('page');
        $sortType = $this->request->param('types');
        $rename = $this->request->param('name');

        error_log($page."=======".$categoryid);
        // 筛选条件
        $filter = [];
        if ($categoryid == -1) {
            $filter['goods_name'] = ['like', '%' . trim($rename) . '%'];
        } else {
            $filter['category_id'] = $categoryid;
        }
        $filter['goods_status'] = '10';
        $filter['is_delete'] = '0';

        // 排序规则
        $sort = [];
        if ($sortType === 'normal') {
            $sort = ['goods_sort' => 'desc', 'goods_id' => 'desc'];
        } elseif ($sortType === 'sales') {
            $sort = ['goods_sales' => 'desc'];
        } elseif ($sortType === 'price') {
            $sort = ['goods_min_price' => 'asc'];
        }
        // 商品表名称
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();

        $listdata = $model_temp->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec'])->where($filter)->order($sort)
            ->paginate(10, false, ['page' => $page]);

        foreach ($listdata as $index => $item) {
            $blistdatarList[] = ['image' => cdnurl(explode(",", $item['images'])[0], true), 'goods_name' => $item['goods_name'],
                'id' => $item['goods_id'], 'goods_min_price' => $item['goods_min_price'], 'goods_max_price' => $item['goods_max_price'], 'goods_sales' => $item['goods_sales']];
        }

        foreach ($listdata as $index => $item){

            $image =  cdnurl(explode(",", $item['images'])[0], true);
            $listdata[$index]['image'] = $image;
        }

        $pagedata = $listdata;
        $this->success('', $pagedata);


    }
}